package com.qf.service.impl;

import com.qf.config.IdWorker;
import com.qf.config.RabbitConfig;
import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.constant.ReportStateConstants;
import com.qf.constant.SourceType;
import com.qf.feign.CacheFeign;
import com.qf.form.SmsInterfaceForm;
import com.qf.model.StandardSubmit;
import com.qf.service.SmsInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/10/18 19:46
 */
@Service
@Slf4j
public class SmsInterfaceServiceImpl implements SmsInterfaceService {
    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Map<String, String> checkInterfaceForm(SmsInterfaceForm form) {
        Map<String, String> resultMap = new HashMap<>();
//        远程调用缓存服务,通过clientId获取客户端对象
        Map<String, String> clientMap = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + form.getClientID());
//        判断客户端对象是否为空,如果为空说明客户端id错误
        if (clientMap == null || clientMap.size() == 0) {
            resultMap.put("code", "101");
            resultMap.put("message", "认证错: clientId错误");
            log.info("[接口模块,clientId认证错误],SmsInterfaceForm={}", form);
            return resultMap;
        }
        /*
         2.校验密码,
         */
        String pwd = clientMap.get("pwd");
        if (form.getPwd().equals(pwd)) {
            resultMap.put("code", "106");
            resultMap.put("message", "认证错: 下行编号(srcID)错误");
            log.info("[接口模块,密码错误],SmsInterfaceForm={}", form);
            return resultMap;
        }
        /*
         3.校验ip
         */
        String ipaddress = clientMap.get("ipaddress");
        if(form.getIp().equals(ipaddress)){
            resultMap.put("code","103");
            resultMap.put("message","IP校验错误");
            log.info("[接口模块,IP地址],SmsInterfaceForm={}",form);
            return resultMap;
        }
        /*
         4.校验短信长度
         */
        if(form.getContent().length()>500){
            resultMap.put("code","104");
            resultMap.put("message","次奥西长度错:为空或超长(目前定位500字)");
            log.info("[接口模块,短信内容过长],SmsInterfaceForm={}",form);
            return resultMap;
        }

        /*
          5.校验手机号
         */
        String mobiles = form.getMobile();
//        分割手机号
        String[] mobilArray = mobiles.split(",");
        if(mobilArray==null || mobilArray.length==0){
            resultMap.put("code","105");
            resultMap.put("message","认证错: 手机号错误");
            log.info("[接口模块,手机号错误],SmsInterfaceForm={}",form);
            return resultMap;
        }
        Set<String> errorMobile=new HashSet<>();
//        校验手机号的正则表达式
        String regix="^{0,1}(13[.-9]|[7-9]|153|156|18[7-9])[0-9]{8}$";
        for (String mobile : mobilArray) {
//            正则表达式校验当前手机号
            if(!mobile.matches(regix)){
//            手机号有问题
                errorMobile.add(mobile);
            }
        }
//        判断手机号是否满足者却需求,如果不满足抛出异常
        if(errorMobile.size()>0){
            resultMap.put("code","105");
            resultMap.put("message","认证错: 手机号错误");
            log.info("[接口模块,手机号错误],errorMobile={}",errorMobile);
            return resultMap;
        }

        /*
          6.校验srcId下行编码
          格式只要是Long类型就行
         */
        try {
            long srcID = Long.parseLong(form.getSrcID());
        } catch (NumberFormatException e) {
            resultMap.put("code","106");
            resultMap.put("message","认证错: 下行编号(srcID)错误");
            log.info("[接口模块,用户下行编码类型错误],SmsInterfaceForm={}",form);
            return resultMap;
        }

        /*
            7.全部成功,封装发送到mq的对象,发送到mq队列
         */

        for (String mobile : mobilArray) {
            StandardSubmit standardSubmit=new StandardSubmit();
//            当前Submit的唯一标识
            standardSubmit.setSequenceId(String.valueOf(idWorker.nextId()));
//            客户端ID
            standardSubmit.setCityId(Integer.parseInt(form.getClientID()));
//            消息的优先级 0 最低 --- 3 最高
            standardSubmit.setMessagePriority(Short.parseShort(clientMap.get("priority")));
//            客户侧唯一序列号
            standardSubmit.setSrcSequenceId(Long.parseLong(form.getSrcID()));
//            下发网关ID号   1   （通道ID）
//            standardSubmit.setGatewayID();
//            目的手机号
            standardSubmit.setDestMobile(mobile);
//            短信内容
            standardSubmit.setMessageContent(form.getContent());
//            短信发送时间
            standardSubmit.setSendTime(new Date());
//            发送方式 1 HTTP 2 WEB
            standardSubmit.setSource(SourceType.HTTP);
//            手机接收的状态值  0 成功 1 等待 2 失败
            standardSubmit.setReportState(ReportStateConstants.WAIT);
//            将短信对象standardSubmit发送到TOPIC_PRE_SEND目前的队列中
            rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_PRE_SEND + "_exchange","routingKey",standardSubmit);
        }
        resultMap.put("code","0");
        resultMap.put("message","接收成功");

        return resultMap;
    }
}
